package io.github.viscent.mtpattern.ch10.tss.example;

import io.github.viscent.util.Debug;

import java.text.DecimalFormat;
import java.util.concurrent.*;

/**
 * 客户端使用ThreadSpecificSecureRandom类来生成验证码并下发验证码短信
 */
public class SmsVerficationCodeSender {

    private static final ThreadFactory THREAD_FACTORY = r -> {
        Thread t = new Thread(r, "VerfCodeSender");
        t.setDaemon(true);
        return t;
    };

    private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(),
        60, TimeUnit.SECONDS, new SynchronousQueue<>(), THREAD_FACTORY, new ThreadPoolExecutor.DiscardPolicy());

    public static void main(String[] args) {
        SmsVerficationCodeSender client = new SmsVerficationCodeSender();
        client.sendVerificationSms("18912345678");
        client.sendVerificationSms("18712345679");
        client.sendVerificationSms("18612345676");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {

        }
    }

    /**
     * 生成并下发验证码短信到指定的手机号码。
     *
     * @param msisdn 短信接收方号码。
     */
    public void sendVerificationSms(final String msisdn) {
        Runnable task = () -> {
            // 生成强随机数验证码
            int verificationCode = ThreadSpecificSecureRandom.INSTANCE.nextInt(999999);
            DecimalFormat df = new DecimalFormat("000000");
            String txtVerCode = df.format(verificationCode);

            sendSms(msisdn, txtVerCode);
        };
        EXECUTOR.submit(task);
    }

    /**
     * 发送验证码短信
     *
     * @param msisdn           短信接收方号码
     * @param verificationCode 验证码
     */
    private void sendSms(String msisdn, String verificationCode) {
        Debug.info("Sending verification code " + verificationCode + " to " + msisdn);

        // 省略其他代码
    }

}
